package io.xxx.omni.oss.sdk

import com.google.gson.JsonObject
import io.xxx.omni.oss.common.toJsonObject
import io.xxx.omni.oss.domain.Store
import org.apache.commons.codec.digest.DigestUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import org.springframework.web.client.RestTemplate
import org.springframework.web.util.UriComponentsBuilder
import java.util.*

@Component
class KsClient {

    @Autowired
    private lateinit var restTemplate: RestTemplate

    private val httpUrl = "https://openapi.kwaixiaodian.com"

    fun execute(store: Store, method: String, request: Map<String, Any>): JsonObject {
        val path = method.replace(".", "-")
        val authorization = store.authorization
        val signMap = TreeMap(request)
        signMap["method "] = method
        signMap["appKey"] = authorization["appKey"]
        signMap["accessToken"] = authorization["accessToken"]
        signMap["version"] = 1
        signMap["signMethod"] = "MD5"
        signMap["timestamp"] = System.currentTimeMillis()
        val builder = StringBuilder()
            .append(signMap.entries.joinToString("&"))
            .append("&").append("signSecret").append("=").append(authorization["signSecret"])
        val sign = DigestUtils.md5Hex(builder.toString()).uppercase()
        val url = UriComponentsBuilder
            .fromHttpUrl(httpUrl)
            .path(path)
            .toUriString()
        signMap["sign"] = sign
        return restTemplate.postForEntity(url, signMap, String::class.java).body!!.toJsonObject()
    }
}